﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Xml.XPath;

namespace NetfractionHub.Security
{
	public class Identity
	{
		private int _identityId;
		private Role _role;

		private Identity()
		{
			_role = null;
			this.Permissions = new Dictionary<Type, AccessState>();
			this.Name = string.Empty;
			this.ClientId = string.Empty;
			this.Password = string.Empty;
			this.NewPasswordRequestActive = false;
			this.IsRegistered = false;
		}

		//SELECT IdentityId, RoleId, ClientId, Name, Password FROM Identities
		public static Identity LoadIdentity(Community.CsharpSqlite.SQLiteClient.SqliteDataReader sdr)
		{
			Identity loadedIdentity = new Identity();

			try
			{
				loadedIdentity._identityId = sdr.GetInt32(0);
				loadedIdentity._role = RoleManager.GetRoleById(Convert.ToByte(sdr.GetInt32(1)));
				loadedIdentity.ClientId = sdr.IsDBNull(2) ? string.Empty : sdr.GetString(2);
				loadedIdentity.Name = sdr.IsDBNull(3) ? string.Empty : sdr.GetString(3);
				loadedIdentity.Password = sdr.IsDBNull(4) ? string.Empty : sdr.GetString(4);

				loadedIdentity.Permissions = IdentityManager.GetIdentityPermissionsByIdentityId(loadedIdentity._identityId);
			}
			catch (InvalidCastException ice)
			{
				Console.WriteLine(ice.Message);
				loadedIdentity = null;
			}
			catch (Exception e)
			{
				Console.WriteLine(e.Message);
				loadedIdentity = null;
			}
			return loadedIdentity;
		}

		public static Identity CreateGenericIdentityForRole(Role role)
		{
			Identity ident = new Identity();

			ident.Name = "Generic Identity";
			ident.IsRegistered = false;
			ident._role = role;

			return ident;
		}

		public Role Role
		{
			get { return _role; }
			set
			{
				_role = value;
				IdentityManager.PersistRole(this);
			}
		}

		public string Name { get; set; }

		public string ClientId { get; set; }

		public string Password { get; set; }

		public bool NewPasswordRequestActive { get; set; }

		public Dictionary<Type, AccessState> Permissions { get; set; }

		public bool IsRegistered { get; set; }

		public string ListPermissions()
		{
			StringBuilder sb = new StringBuilder();
			foreach (KeyValuePair<Type, AccessState> perm in Permission.GetSuperimposition(this.Permissions, _role.Permissions))
			{
				sb.AppendLine(String.Format("Permission Name: {0}, Access: {1}", perm.Key, perm.Value));
			}
			return sb.ToString();
		}
	}
}
